<script lang="ts" setup>
import type { SchoolApi } from '#/api/edu/base/school';

import {
  defineEmits,
  defineExpose,
  defineProps,
  onMounted,
  onUnmounted,
  ref,
  unref,
  watch,
  watchEffect,
} from 'vue';

import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { Button, Card, Empty, message, PageHeader, Tabs } from 'ant-design-vue';

import {
  createSchool,
  getSchoolByLogin,
  updateSchool,
} from '#/api/edu/base/school';
import { $t } from '#/locales';

import BasicInfo from './edit/base-info.vue';
import ContactList from './edit/contact-list.vue';
import EducationForm from './edit/education-form.vue';
import ExternalList from './edit/external-list.vue';
import FeaturesForm from './edit/features-form.vue';
import IntroductionForm from './edit/introduction-form.vue';
import LocationForm from './edit/location-form.vue';
import MembershipForm from './edit/membership-form.vue';
import QualificationForm from './edit/qualification-form.vue';
import BaseDetail from './modules/base-detail.vue';
import ContactDetail from './modules/contact-detail.vue';
import EducationDetail from './modules/education-detail.vue';
import ExternalDetail from './modules/external-detail.vue';
import FeaturesDetail from './modules/features-detail.vue';
import IntroductionDetail from './modules/introduction-detail.vue';
import LocationDetail from './modules/location-detail.vue';
import MembershipDetail from './modules/membership-detail.vue';
import QualificationDetail from './modules/qualification-detail.vue';
import StatusDetail from './modules/status-detail.vue';

const props = defineProps<{
  createFlag?: boolean; // 是否创建模式
  id?: String;
  isCampus?: boolean; // 学校操作校区，部分字段不可编辑模式
}>();
const emit = defineEmits(['success']);
const activeAnchor = ref('base-info');
const formData = ref<SchoolApi.School>({} as SchoolApi.School);
/** 表单引用 */
const basicInfoRef = ref<InstanceType<typeof BasicInfo>>();
const membershipInfoRef = ref<InstanceType<typeof MembershipForm>>();
const locationInfoRef = ref<InstanceType<typeof LocationForm>>();
const educationInfoRef = ref<InstanceType<typeof EducationForm>>();
const featuresInfoRef = ref<InstanceType<typeof FeaturesForm>>();
const qualificationInfoRef = ref<InstanceType<typeof QualificationForm>>();
const introductionInfoRef = ref<InstanceType<typeof IntroductionForm>>();
const contactInfoRef = ref<InstanceType<typeof ContactList>>();
const externalListRef = ref<InstanceType<typeof ExternalList>>();
const activeKeys = ref('1'); // 默认展开基础
const desensitize = ref<boolean>(true); // 是否脱敏
const loading = ref<boolean>(false); // 是否加载中
function handleDesensitize() {
  desensitize.value = !desensitize.value;
  getInfo();
}
const isEdit = ref<boolean>(false); // 是否编辑
function handleEdit() {
  desensitize.value = false;
  isEdit.value = true;
  getInfo();
}
async function getInfo() {
  const data = await getSchoolByLogin(
    props.id === '0' ? undefined : props.id,
    desensitize.value,
  );
  const school = { ...data, isCampus: props.isCampus || false };
  if (props.createFlag && school.isCampus) {
    // 新增校区

    isEdit.value = true;
    school.parentSchoolId = school.id;
    school.parentSchoolName = school.schoolName;
    school.schoolName = '';
    school.shortName = '';
    school.schoolNum = '';
    school.schoolCampusType = 2;
    school.id = undefined;
  }
  formData.value = school;
}
async function tabChange(key: string) {
  if (key === '3') {
    const membershipValues = (await membershipInfoRef.value?.getValues()) ?? {};
    formData.value = { ...formData.value, ...membershipValues };
  }
}
async function handleSave() {
  const formRefs = [
    { ref: basicInfoRef, label: '基本信息', key: '1' },
    { ref: membershipInfoRef, label: '行政隶属关系', key: '2' },
    { ref: locationInfoRef, label: '位置信息', key: '4' },
    { ref: educationInfoRef, label: '办学属性', key: '5' },
    { ref: featuresInfoRef, label: '教学特色', key: '6' },
    { ref: qualificationInfoRef, label: '资质认证', key: '7' },
    { ref: introductionInfoRef, label: '学校介绍', key: '9' },
  ];

  // 校验所有表单
  for (const { ref, label, key } of formRefs) {
    if (key !== activeKeys.value) continue; // 跳过未展开
    const valid = await ref.value?.validate();
    if (!valid) {
      message.warn(`保存失败，原因：${label}表单校验失败，请检查！`);
      return;
    }
  }
  loading.value = true;
  try {
    // 收集表单值
    const values = await Promise.all(
      formRefs.map(({ ref }) => ref.value?.getValues() ?? {}),
    );
    const contactList = await contactInfoRef.value?.getValues();
    // 合并所有值
    const data = Object.assign({}, unref(formData), ...values, {
      contacts: contactList,
    });

    const res = await (formData.value?.id
      ? updateSchool(data)
      : createSchool(data));
    // 关闭并提示

    isEdit.value = false;
    if (props.createFlag) {
      emit('success', res);
    } else {
      getInfo();
    }

    message.success($t('ui.actionMessage.operationSuccess'));
    loading.value = false;
  } finally {
    loading.value = false;
  }
}
async function handleClose() {
  isEdit.value = false;
  getInfo();
}
// 处理锚点点击事件，避免页面刷新
const handleAnchorClick = (e: MouseEvent) => {
  e.preventDefault();
  const targetId = (e.currentTarget as HTMLElement).dataset.target;
  if (targetId) {
    activeAnchor.value = targetId;
    const element = document.getElementById(targetId);
    if (element) {
      // 添加平滑滚动效果
      element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }
};

// 处理滚动事件，更新活动锚点
const handleScroll = () => {
  const sections = document.querySelectorAll('.section');
  let currentSectionId = 'base-info';
  let minDistance = Infinity;

  sections.forEach((section) => {
    const rect = section.getBoundingClientRect();
    // 计算距离视口顶部的距离
    const distance = Math.abs(rect.top - 100); // 100 是 offsetTop

    if (distance < minDistance) {
      minDistance = distance;
      currentSectionId = section.id;
    }
  });

  activeAnchor.value = currentSectionId;
};

// 组件挂载时添加滚动监听
onMounted(() => {
  const contentArea = document.querySelector('.content-area');
  if (contentArea) {
    contentArea.addEventListener('scroll', handleScroll);
    // 初始检查当前位置
    handleScroll();
  }
  getInfo();
});

// 组件卸载时移除滚动监听
onUnmounted(() => {
  const contentArea = document.querySelector('.content-area');
  if (contentArea) {
    contentArea.removeEventListener('scroll', handleScroll);
  }
});

// 当 schoolData 加载完成后，更新活动锚点
watchEffect(() => {
  if (formData.value.id) {
    setTimeout(() => {
      handleScroll();
    }, 100);
  }
});
watch(
  () => props.id,
  (newValue) => {
    if (newValue) {
      getInfo();
    }
  },
);
// 对外暴露handleEdit方法
defineExpose({
  handleEdit,
});
</script>

<template>
  <Page auto-content-height>
    <PageHeader
      v-if="formData?.id || props.createFlag"
      style="border: 1px solid rgb(235 237 240); border-radius: 5px"
      :ghost="false"
      :title="formData.schoolName || '新增学校信息'"
    >
      <template #extra>
        <Button
          type="primary"
          v-if="!isEdit"
          @click="handleDesensitize"
          :danger="desensitize"
        >
          <IconifyIcon
            :icon="
              desensitize
                ? 'ant-design:eye-filled'
                : 'ant-design:eye-invisible-filled'
            "
          />
          {{ desensitize ? '关闭脱敏' : '启用脱敏' }}
        </Button>
        <Button type="primary" v-if="!isEdit" @click="handleEdit">
          编辑
        </Button>
        <Button
          type="primary"
          v-if="isEdit"
          @click="handleSave"
          :loading="loading"
          :disabled="loading"
        >
          保存
        </Button>
        <Button v-if="isEdit" @click="handleClose"> 关闭 </Button>
      </template>
      <Tabs
        v-model:active-key="activeKeys"
        tab-position="left"
        @change="tabChange"
        v-if="isEdit"
      >
        <Tabs.TabPane key="1" tab="基础信息">
          <div class="w-[60%]">
            <BasicInfo ref="basicInfoRef" :school="formData" />
          </div>
        </Tabs.TabPane>
        <Tabs.TabPane key="2" tab="行政隶属关系">
          <div class="w-[60%]">
            <MembershipForm ref="membershipInfoRef" :school="formData" />
          </div>
        </Tabs.TabPane>
        <Tabs.TabPane key="3" tab="负责人">
          <ContactList
            ref="contactInfoRef"
            :school-contacts="formData.contacts || []"
          />
        </Tabs.TabPane>
        <Tabs.TabPane key="4" tab="位置信息">
          <div class="w-[60%]">
            <LocationForm ref="locationInfoRef" :school="formData" />
          </div>
        </Tabs.TabPane>
        <Tabs.TabPane key="5" tab="办学属性">
          <div class="w-[60%]">
            <EducationForm ref="educationInfoRef" :school="formData" />
          </div>
        </Tabs.TabPane>
        <Tabs.TabPane key="6" tab="教学特色">
          <div class="w-[60%]">
            <FeaturesForm ref="featuresInfoRef" :school="formData" />
          </div>
        </Tabs.TabPane>
        <Tabs.TabPane key="7" tab="资质认证">
          <div class="w-[60%]">
            <QualificationForm ref="qualificationInfoRef" :school="formData" />
          </div>
        </Tabs.TabPane>
        <Tabs.TabPane key="9" tab="学校介绍">
          <IntroductionForm ref="introductionInfoRef" :school="formData" />
        </Tabs.TabPane>
        <Tabs.TabPane
          key="10"
          tab="与外部系统关系"
          v-if="formData.id"
          v-access:code="['system:dept-external:query']"
        >
          <ExternalList ref="externalListRef" :school-id="formData.id" />
        </Tabs.TabPane>
      </Tabs>
      <div v-else class="detail-container">
        <!-- 左侧锚点导航 -->
        <div class="anchor-sidebar">
          <div class="custom-anchor">
            <div
              class="anchor-link"
              :class="[{ active: activeAnchor === 'base-info' }]"
              data-target="base-info"
              @click="handleAnchorClick"
            >
              基本信息
            </div>
            <div
              class="anchor-link"
              :class="[{ active: activeAnchor === 'membership-info' }]"
              data-target="membership-info"
              @click="handleAnchorClick"
            >
              行政隶属关系
            </div>
            <div
              class="anchor-link"
              :class="[{ active: activeAnchor === 'contact-info' }]"
              data-target="contact-info"
              @click="handleAnchorClick"
            >
              负责人
            </div>
            <div
              class="anchor-link"
              :class="[{ active: activeAnchor === 'location-info' }]"
              data-target="location-info"
              @click="handleAnchorClick"
            >
              位置信息
            </div>
            <div
              class="anchor-link"
              :class="[{ active: activeAnchor === 'education-info' }]"
              data-target="education-info"
              @click="handleAnchorClick"
            >
              办学属性
            </div>
          </div>
          <div class="custom-anchor">
            <div
              class="anchor-link"
              :class="[{ active: activeAnchor === 'features-info' }]"
              data-target="features-info"
              @click="handleAnchorClick"
            >
              教学特色
            </div>
          </div>
          <div class="custom-anchor">
            <div
              class="anchor-link"
              :class="[{ active: activeAnchor === 'qualification-info' }]"
              data-target="qualification-info"
              @click="handleAnchorClick"
            >
              资质认证
            </div>
          </div>
          <div class="custom-anchor">
            <div
              class="anchor-link"
              :class="[{ active: activeAnchor === 'status-info' }]"
              data-target="status-info"
              @click="handleAnchorClick"
            >
              状态信息
            </div>
          </div>
          <!-- 学校简介 -->
          <div class="custom-anchor">
            <div
              class="anchor-link"
              :class="[{ active: activeAnchor === 'introduction-info' }]"
              data-target="introduction-info"
              @click="handleAnchorClick"
            >
              学校简介
            </div>
          </div>
          <div class="custom-anchor">
            <div
              class="anchor-link"
              :class="[{ active: activeAnchor === 'external-info' }]"
              data-target="external-info"
              @click="handleAnchorClick"
            >
              与其他系统关系
            </div>
          </div>
        </div>

        <!-- 右侧内容区域 -->
        <div class="content-area">
          <!-- 基本信息 -->
          <div id="base-info" class="section">
            <Card title="基本信息" class="mb-2">
              <BaseDetail :school="formData" />
            </Card>
          </div>

          <!-- 行政隶属关系 -->
          <div id="membership-info" class="section">
            <Card title="行政隶属关系" class="mb-2">
              <MembershipDetail :school="formData" />
            </Card>
          </div>

          <!-- 负责人 -->
          <div id="contact-info" class="section">
            <ContactDetail
              :school="formData"
              :desensitize="desensitize"
              :show-desensitize-button="false"
              @change-desensitize="handleDesensitize"
            />
          </div>

          <!-- 位置信息 -->
          <div id="location-info" class="section">
            <Card title="位置信息" class="mb-2">
              <LocationDetail :school="formData" />
            </Card>
          </div>

          <!-- 办学属性 -->
          <div id="education-info" class="section">
            <Card title="办学属性" class="mb-2">
              <EducationDetail :school="formData" />
            </Card>
          </div>

          <!-- 教学特色 -->
          <div id="features-info" class="section">
            <Card title="教学特色" class="mb-2">
              <FeaturesDetail :school="formData" />
            </Card>
          </div>

          <!-- 资质认证 -->
          <div id="qualification-info" class="section">
            <Card title="资质认证" class="mb-2">
              <QualificationDetail :school="formData" />
            </Card>
          </div>

          <!-- 状态信息 -->
          <div id="status-info" class="section">
            <Card title="状态信息" class="mb-2">
              <StatusDetail :school="formData" />
            </Card>
          </div>
          <!-- 学校简介 -->
          <div id="introduction-info" class="section">
            <Card title="学校简介" class="mb-2">
              <IntroductionDetail :school="formData" />
            </Card>
          </div>

          <!-- 与其他系统关系 -->
          <div id="external-info" class="section">
            <ExternalDetail :school-id="formData.id" />
          </div>
        </div>
      </div>
    </PageHeader>
    <Card v-else>
      <Empty description="您的的账号不是学校用户，不能操作" />
    </Card>
  </Page>
</template>
<style scoped>
/* 响应式设计 */
@media (max-width: 768px) {
  .detail-container {
    flex-direction: column;
    height: auto;
  }

  .anchor-sidebar {
    width: 100%;
    height: auto;
    max-height: 200px;
    padding-right: 0;
    margin-bottom: 16px;
    border-right: none;
    border-bottom: 1px solid #f0f0f0;
  }

  .content-area {
    padding: 0;
  }

  .section {
    margin-bottom: 10px;
    scroll-margin-top: 100px;
  }

  .ant-card {
    margin-bottom: 16px;
  }
}

@media (max-width: 480px) {
  .anchor-sidebar :deep(.ant-anchor-link-title) {
    padding: 3px 6px;
    font-size: 13px;
  }

  .ant-card-head-title {
    font-size: 14px;
  }
}

.detail-container {
  display: flex;
  gap: 24px;
  height: calc(100vh - 100px);
  padding: 16px 0;
  overflow: hidden;
}

/* 左侧锚点导航 */
.anchor-sidebar {
  flex-shrink: 0;
  width: 160px;
  padding-right: 16px;
  overflow-y: auto;
  border-right: 1px solid #f0f0f0;
}

/* 自定义锚点样式 */
.custom-anchor {
  padding: 0;
}

.anchor-link {
  display: inline-block;
  width: 100%;
  padding: 10px 8px;
  margin-bottom: 4px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.anchor-link:hover {
  color: #1890ff;
  background-color: #f5f5f5;
}

.anchor-link.active {
  font-weight: 500;
  color: #1890ff;
  background-color: #e6f7ff;
}

/* 右侧内容区域 */
.content-area {
  flex: 1;
  padding: 0 16px;
  overflow-y: auto;
}

.section {
  margin-bottom: 12px;
  scroll-margin-top: 120px;
}

/* 优化卡片样式 */
.ant-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 5%);
  transition: all 0.3s ease;
}

.ant-card:hover {
  box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
}

.ant-card-head {
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.ant-card-head-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 滚动条样式 */
.content-area::-webkit-scrollbar,
.anchor-sidebar::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.content-area::-webkit-scrollbar-track,
.anchor-sidebar::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.content-area::-webkit-scrollbar-thumb,
.anchor-sidebar::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
  transition: background 0.3s ease;
}

.content-area::-webkit-scrollbar-thumb:hover,
.anchor-sidebar::-webkit-scrollbar-thumb:hover {
  background: #999;
}

/* 主容器样式 */
</style>
